package com.fingard.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpHelper {

	public static String getLocalHostIp(){
        try {
        	
        	InetAddress addr = InetAddress.getLocalHost();
        	String ip1=addr.getHostAddress().toString();//获得本机IP
        	if(!ip1.equals("127.0.0.1") && ip1.indexOf(".")>0 && !ip1.contains(":"))
            {
        		return ip1;
            }
        	
        	Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {      
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
             while (ips.hasMoreElements()) {
            	 String ipTemp= ips.nextElement().getHostAddress();
                 if(!ipTemp.equals("127.0.0.1") && ipTemp.indexOf(".")>0 && !ipTemp.contains(":"))
                 {
                     return ipTemp;
                 }
             }
            }
        }catch(Exception ee)
        {
            ee.printStackTrace();   
        }
        return "localhost";
	}
}
